package com.ihm.projetihm_v1.activity.main;

import java.io.File;
import java.util.LinkedList;
import java.util.List;

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.ActionBar.TabListener;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import com.ihm.projetihm_v1.MyApplication;
import com.ihm.projetihm_v1.R;
import com.ihm.projetihm_v1.activity.preferences.PreferencesActivity;
import com.ihm.projetihm_v1.image.fragmentManager.ImageFragment;
import com.ihm.projetihm_v1.image.fragmentManager.ImageFragment.MY_TABS;
import com.ihm.projetihm_v1.nf.Graphe;
import com.ihm.projetihm_v1.nf.LinkedPhoto;
import com.ihm.projetihm_v1.nf.communication.CommunicationFS;

/**
 * This is the main activity : home page
 * 
 * @author Adrien
 *
 */
public class MainActivity
		extends Activity
{

    /**
     * The serialization (saved instance state) Bundle key representing the
     * current tab position.
     */
    private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item";

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        try{
	        this.initApplication();
        }
        catch (Exception e)
        {
        	MyApplication app = (MyApplication) this.getApplication();
        	app.end(this, e.toString());
        	return;
        }
	
        // Set up the action bar to show tabs.
        final ActionBar actionBar = getActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        // For each of the sections in the application, add a tab to the action bar.
        for (MY_TABS tab : MY_TABS.values())
        {
            actionBar.addTab(actionBar.newTab().setText(tab.getTitleResID())
            		.setTabListener(new MyTabListener(this)));
        }
    }
    
    private void initApplication()
    		throws Exception
    {
    	MyApplication app = (MyApplication) this.getApplication();
    	app.setIsMainActivity(true);
    	if ( ! app.isInitialized())
    	{
    		app.setInitialized();

            // create root directory
    		this.controlRootDirectory(app);
    		
    		// graphe
    		this.manageGraph(app);
    	}
    }
    
    private void controlRootDirectory(MyApplication app)
    		throws Exception
    {
        String root = Environment.getExternalStorageDirectory().getPath()
        		+ "/Android/data/"
        		+ this.getApplicationContext().getPackageName()
        		+ "/files";
        CommunicationFS fs = new CommunicationFS(root);
		app.setCommunicationFS(fs);
    }
    
    private void manageGraph(MyApplication app)
    {
		List<Graphe<LinkedPhoto>> graphsList = new LinkedList<Graphe<LinkedPhoto>>();
		CommunicationFS fs = app.getCommunicationFS();
		File[] dirs = fs.getContentDirectory("");
		for (File dir : dirs)
		{
			if (dir.isDirectory())
			{
				try{
					Graphe<LinkedPhoto> graphe = LinkedPhoto.computeLinks(dir);
					File panorama = new File (dir, "panorama.jpg");
					if ( ! panorama.isFile())
					{
						throw new Exception("Panorama does not exist in dir " + dir.getName());
					}
					graphe.setPanorama(panorama);
					graphsList.add(graphe);
				}
				catch (Exception e)
				{
					// do nothing for this directory : relations does not exist
					System.out.println("PROBLEM RELATIONS : directory "
							+ dir.getName() + " > exception message > "
							+ e.getMessage());
				}
			}
		}
		
		app.setMainGraphsList(graphsList);
    }

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState)
    {
        // Restore the previously serialized current tab position.
        if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM))
        {
            getActionBar().setSelectedNavigationItem(
                    savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM));
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState)
    {
        // Serialize the current tab position.
        outState.putInt(STATE_SELECTED_NAVIGATION_ITEM,
                getActionBar().getSelectedNavigationIndex());
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.menu_synchronize:
            	this.synchroniser();
                return true;
            case R.id.menu_settings:
    			Intent intent = new Intent(this, PreferencesActivity.class);
    			startActivity (intent);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    
    private void synchroniser()
    {
    	Toast.makeText(
    			this,
    			"Synchronisation !",
    			Toast.LENGTH_SHORT)
    			.show();
    }
    
    public static class MyTabListener
    		implements TabListener
    {
    	private Fragment mFragment;
    	private final Activity mActivity;
    	
    	public MyTabListener(Activity activity)
    	{
    		this.mActivity = activity;
    	}

		@Override
		public void onTabReselected(Tab tab, FragmentTransaction ft){}

		@Override
		public void onTabSelected(Tab tab, FragmentTransaction ft)
		{
			// Check if the fragment is already initialized
			if (this.mFragment == null)
			{
				// If not, instantiate and add it to the activity
				this.mFragment = Fragment.instantiate(this.mActivity, ImageFragment.class.getName());
				this.mFragment.setRetainInstance(true);
				// with good argument
				int tabPosition = tab.getPosition();
	            Bundle args = new Bundle();
	            args.putInt(
	            		ImageFragment.CST_ARG_SECTION_NUMBER,
	            		tabPosition);
	            this.mFragment.setArguments(args);
	            
				ft.add(
						android.R.id.content,
						this.mFragment,
						"tabTag" + tabPosition);
			} else {
				// If it exists, simply attach it in order to show it
				ft.attach(this.mFragment);
			}
		}

		@Override
		public void onTabUnselected(Tab tab, FragmentTransaction ft)
		{
			 if (this.mFragment != null)
			 {
				 ft.detach(this.mFragment);
			 }
		}
    }
}
